﻿using Audit.EntityFramework.Core.Samples.Data;
using Audit.EntityFramework.Core.Samples.DTOs;
using Audit.EntityFramework.Core.Samples.Models;
using Microsoft.AspNetCore.Mvc;

namespace Audit.EntityFramework.Core.Samples.Controller;

[ApiController]
[Route("api/[controller]/[action]")]
public class TodoItemsController(ApplicationDbContext context) :   ControllerBase
{
    [HttpPost]
    public IActionResult CreateTodoItem([FromBody]TodoItemCreateDto dto)
    {
        var item = new TodoItem
        {
            Title = dto.Title,
            IsDone = dto.IsDone
        };
        context.TodoItems.Add(item);
        context.SaveChanges();
        return Ok(item.Id);
    }
    
    [HttpPut("{id:guid}")]
    public IActionResult UpdateTodoItem(Guid id, [FromBody]TodoItemUpdateDto item)
    {
        var todoItem = context.TodoItems.Find(id);
        if (todoItem == null)
        {
            return NotFound();
        }
        
        // 直接修改属性，让 EF Core 自动跟踪变更
        // 不需要显式调用 context.Update()
        todoItem.Title = item.Title;
        todoItem.IsDone = item.IsDone;
        
        context.SaveChanges();
        return Ok(todoItem.Id);
    }
    
    [HttpDelete("{id}")]
    public IActionResult DeleteTodoItem(Guid id)
    {
        var todoItem = context.TodoItems.Find(id);
        if (todoItem == null)
        {
            return NotFound();
        }
        context.TodoItems.Remove(todoItem);
        context.SaveChanges();
        return Ok();
    }
}
